<template>
  <view class="select-city-box">
    <!-- 侧导航 -->
    <scroll-view
      scroll-y
      class="city-nav-control"
      scroll-with-animation
      :scroll-into-view="`city-nav-control-${navCurrent}`">
      <basic-skeleton
        :loading="loading"
        :list="leftSkeleton"
        animate >
        <view
          class="city-nav-item"
          v-for="(item, index) in tabList"
          :class="{'active': index === navCurrent}"
          :key="index"
          :id="'city-nav-control-'+index"
          @click="handleTabChange(index)">
          <view class="nav-content">{{item.title}}</view>
        </view>
      </basic-skeleton>
      <!-- 安全区 -->
      <basic-safe-area />
    </scroll-view>

    <!-- 主体区域 -->
    <scroll-view
      scroll-y
      class="city-container"
      scroll-with-animation
      :scroll-into-view="`city-category-${current}`"
      @scroll="handleScroll" >
      <basic-skeleton
        :loading="loading"
        :list="rightSkeleton"
        animate >
        <!-- 定位、最近浏览 -->
        <view v-if="showLocationTab" id="city-category-0">
          <view class="province-normal-title">{{locationTitle}}</view>
          <view class="tags-container">
            <!-- 定位城市 -->
            <view class="tag-item active" @click="localCityItemClick">
              <template>
                <basic-icons name="icon111"></basic-icons> {{locationStatus}}
              </template>
            </view>
            <!-- 最近浏览 -->
            <view
              class="tag-item"
              v-for="(item, index) in lastest" 
              :key="index"
              @click="clickItem(item)">
              {{item.name}}
            </view>
          </view>
        </view>

        <view 
          v-for="(category, categoryIndex) in tabList"
          :key="categoryIndex"
          :id="'city-category-'+categoryIndex">
          <!-- 标题 -->
          <view class="province-normal-title">
            {{category.subTitle || category.title}}
          </view>

          <template v-if="category.cities && category.cities.length">

            <!-- 图片列表 -->
            <template v-if="category.cities[0].img">
              <view class="images-container">
                <view class="image-item"
                  v-for="(item, index) in category.cities" 
                  :key="index"
                  @click="clickItem(item)">
                  <image class="city-image" :src="item.img" />
                  <view class="city-name">{{item.name}}</view>
                </view>
              </view>
            </template>

            <!-- 城市名称列表 -->
            <template v-else>
              <view class="tags-container">
                <view
                  class="tag-item"
                  v-for="(item, index) in category.cities" 
                  :key="index"
                  @click="clickItem(item)">
                  {{item.name}}
                </view>
              </view>
            </template>

          </template>

          <template v-else>
            <view class="empty-class">当前分类无推荐城市</view>
          </template>
        </view>
      </basic-skeleton>
      
      <!-- 安全区 -->
      <basic-safe-area />
    </scroll-view>

    <!-- 定位弹窗提示 -->
    <uni-popup ref="distancePopup" type="center" >
      <view class="position-dialog--wrap">
        <view>
          <image class="image" src="/static/position.png">             
        </view>
        <view class="title">定位数据获取失败</view> 
        <view class="title">请检查定位服务是否已经开启</view> 
        <view class="btn" @click="clodeDistancePopup">确定</view> 
      </view>
    </uni-popup>
  </view>
  
</template>
<script>
import { throttle } from "utils/helper/throttle"
import sdk from "sdk"
import modal from "utils/helper/modal"
import {getCityList} from 'api'
import city from '@/mixins/city'
import {leftSkeleton, rightSkeleton} from '../skeleton'
import { HOT_CITYS } from '@/model/enum'
import storage from 'utils/helper/storage'

export default {
  name: 'select-city-box',
  mixins: [city],
  props: {
    options: { 
      type:Object, 
      default: ()=>({ productType: 0 })
    },
    showLocation: {
      type: Boolean,
      default: false
    },
    showHistory: {
      type: Boolean,
      default: false
    },
    showHot: {
      type: Boolean,
      default: false
    },
  },

  data() {
    return {
      loading: true,
      leftSkeleton: leftSkeleton, // 骨架图配置
      rightSkeleton: rightSkeleton, // 骨架图配置
      // 为了防止双边滚动互相影响，开设2个索引值
      navCurrent: 0, // 左侧导航当前激活索引
      current: 0, // 右侧内容当前位置

      locationTitle: '定位/最近浏览', // 定位、最近浏览的标题
      showLocationTab: true, // 是否显示'定位/最近浏览'

      // 缓存城市数据
      hotRegions: [
        { // 热门城市，regionId为数据库固定值，不要动
          title: '热门',
          subTitle: '热门城市',
          cities: HOT_CITYS
        }
      ],
      tabList: [],
      lastest: [], // 从缓存获取

      location: {}, // 当前定位
      locationTimeout: false,
      locationStatus: '定位中...',
    }
  },

  created() {
    if (!this.showHot) this.hotRegions = []

    // 更新最近浏览的城市
    if (this.showHistory) {
      this.lastest = this.$city_getLatestCity()
    }

    if(this.showLocation) this.getLocation()

    if (!this.showLocation) {
      this.locationTitle = '最近浏览'
    } else if(!this.showHistory) {
      this.locationTitle = '定位'
    }

    if (!this.showLocation && !this.showHistory) {
      this.showLocationTab = false
      this.current = 1
    }
    
    this.getCityList()
  },

  methods: {
    getCityList() {
      // 从链接拿参数
      let params = { productType: 0}
      if(this.options && this.options.productType){
        params.productType = this.options.productType
      }
      getCityList(params, (res) => {
        this.loading = false
        let allCities = []
        let { provinceInfos = [], directlyRegionInfos = [] } = res.result || {}

        allCities.push({
          title: '直辖市',
          cities: directlyRegionInfos
        })

        provinceInfos.forEach((province) => {
          allCities.push({
            title: province.province,
            cities: province.cities
          })
        })

        this.tabList = [
          ...this.hotRegions,
          ...allCities
        ]
      })
    },
    handleTabChange(index) {
      let category = this.tabList[index]

      this.navCurrent = index
      this.current = index
    },
    handleScroll(e) {
      // 监听滚动行为，更新左侧菜单的激活状态
      throttle(() => {
        sdk.getAllOffset('.province-normal-title', '.city-container', this).then(
          (res) => {
            res.forEach((child, index) => {
              if (
                e.detail.scrollTop >= child.top
              ) {
                this.navCurrent = this.showLocationTab ? index : index + 1
              }
            })
          }
        )
      }, 100);
    },

    getLocation() {
      this.locationTimeout = false
      this.locationStatus = '定位中...'

      this.$city_getLocation()
      .then(res => {
        this.location = res
        this.locationStatus = res.city
        this.locationTimeout = false
      })
      .catch(res => {
        if (res && res.msgCode === -1) {
          this.locationTimeout = true
          this.locationStatus = '定位超时'
        } else {
          this.locationStatus = '定位失败'
          this.locationTimeout = false
        }

        // 弹窗显示
        this.localCityItemClick()
      })
    },

    clodeDistancePopup() {
      this.$refs.distancePopup.close()
    },

    localCityItemClick() {
      if (this.locationStatus == '定位中...') return

      if (this.locationTimeout) { // 定位超时，重新定位
        this.getLocation()
      } else if (!this.location || !this.location.city) { // 定位失败
        // 弹窗显示
        this.$refs.distancePopup.open()
      } else { // 已定位成功，则选中城市
        this.clickItem({
          regionId: this.location.regionId,
          name: this.location.city
        })
      }
    },

    clickItem(item) {
      // 选中参数传回上一页
      sdk.selectCity({
        regionId: String(item.regionId),
        name: item.name,
        country: 0
      })
      
      // 更新最近浏览的城市
      if (this.options.productType >= 0) {
        this.$city_updateLatestCity(item)
      }

      sdk.navigateBack()
    }
  }
}
</script>
<style lang="less">
.select-city-box {
  .flex;
  height: 100%;

  .nav-content{
    color: @font_light_color;
    font-size: 28rpx;
    line-height: 1;
    padding: 36rpx 0;
  }
  .province-normal-title {
    color: red;
    font-size: 24rpx;
    color: @font_light_color;
    line-height: 1;
    padding: 36rpx 0;
  }

  .city-nav-control {
    width: 134rpx;
    background-color: #F1F4F9;
    // height: 100%;

    .city-nav-item {
      position: relative;
      height: 96rpx;
      line-height: 96rpx;
      text-align: center;

      background-color: #F1F4F9;

      &.active {
        background-color: #ffffff;

        &:before {
          content: "";
          position: absolute;
          left: 0;
          top: 30rpx;
          display: inline-block;
          width: 8rpx;
          height: 36rpx;
          background: @theme_color;
          border-radius: 0 200rpx 200rpx 0;
        }
      }
    }
  }

  .city-container {
    .flex-1;

    padding: 0 40rpx;
    background-color: #ffffff;

    scrollbar-width: none; /* Firefox */

    .images-container{
      .flex;
      .flex-wrap;
      .flex-between;

      padding-bottom: 12rpx;

      .image-item {
        position: relative;
        width: 264rpx;
        height: 128rpx;

        border-radius: 8rpx;
        overflow: hidden;

        margin-bottom: 8rpx;

        color: #ffffff;
      }

      .city-image {
        width: 100%;
        height: 100%;
      }

      .city-name {
        .line-ellipsis;
        position: absolute;
        top: 44rpx;

        width: 100%;
        height: 40rpx;
        line-height: 40rpx;
        text-align: center;

        margin: auto 0;
      }
    }

    .tags-container {
      .flex;
      .flex-wrap;

      .tag-item {
        .line-ellipsis;

        width: 166rpx;
        height: 64rpx;
        line-height: 64rpx;
        border-radius: 32rpx;

        padding: 0 8rpx;
        margin-right: 18rpx;
        margin-bottom: 20rpx;
        
        text-align: center;
        background-color: #F1F4F9;
        box-sizing: border-box;

        &:nth-child(3n) {
          margin-right: 0;
        }

        &.active,
        &:active {
          color: @theme_color;
          background-color: fade(@theme_color, 5%);
          border: 2rpx solid @theme_color;
        }
      }
    }
  }

  .position-dialog--wrap{
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    border-radius:16rpx;
    background: #fff;
    & > view{
      margin-bottom: 30rpx;
    }
    .image{
      width: 520rpx;
      height: 376rpx;
    }
    .title{
      font-size: 28rpx;
    }
    .btn{
      width: 380rpx;
      height: 64rpx;
      background: @theme_color;
      border-radius: 39rpx;
      color: #fff;
      font-size: 28rpx;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .cancel{
      font-size: 24rpx;
      color: #8A95AC;
    }
  }
}
</style>
